Passed
Push — master ( 227b43...81878e )
by Pavel
01:19
created

index.ts ➔ printSummary   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
import * as core from '@actions/core';
2
import {HttpClient} from '@actions/http-client';
3
import {Octokit} from '@octokit/rest';
4
import {config} from 'dotenv';
5
import {resolve} from 'path';
6
import formatLine from './formatLine';
7
8
config({path: resolve(__dirname, '../.env')});
9
10
const GH_TOKEN = core.getInput('GH_TOKEN', {required: true});
11
const WAKA_API_KEY = core.getInput('WAKA_API_KEY', {required: true});
12
const GIST_ID = core.getInput('GIST_ID', {required: true});
13
const MAX_RESULT = Number(core.getInput('MAX_RESULT', {required: true}));
14
const DATE_RANGE = core.getInput('DATE_RANGE', {required: false});
15
const PRINT_SUMMARY = core.getBooleanInput('PRINT_SUMMARY', {required: true});
16
const USER_AGENT = 'WakaTime-Gist/1.3 +https://github.com/marketplace/actions/wakatime-gist';
17
const ACTION_URL = 'https://github.com/marketplace/actions/wakatime-gist';
18
19
const updateDate = new Date().toLocaleDateString('en-us', {day: 'numeric', year: 'numeric', month: 'short'});
20
const summaryTable: any[] = [[{data: 'Action', header: true}, {data: 'Result', header: true}]];
21
22
let range: string = DATE_RANGE;
23
if (!['last_7_days', 'last_30_days', 'last_6_months', 'last_year'].includes(range)) range = 'last_7_days';
24
25
let title: string = 'Latest';
26
if (range === 'last_7_days') title = 'Weekly';
27
if (range === 'last_30_days') title = 'Monthly';
28
title = title + ' statistics [update ' + updateDate + ']';
29
30
(async () => {
31
  /**
32
   * Get statistics
33
   */
34
  const httpClient = new HttpClient(USER_AGENT);
35
  const response = await httpClient.getJson('https://wakatime.com/api/v1/users/current/stats/' + range,
36
    {Authorization: `Basic ${Buffer.from(WAKA_API_KEY).toString('base64')}`})
37
    .catch(error => core.setFailed('Action failed with error: ' + error.message));
38
39
  // @ts-ignore
40
  const languages: any[] = response.result.data.languages;
41
  if (!languages) {
42
    summaryTable.push(['Statistics received', '✔']);
43
  } else {
44
    core.setFailed('Action failed with error: empty response from wakatime.com');
45
  }
46
47
  /**
48
   * Formatting
49
   */
50
  let otherTotalSeconds = 0;
51
  let otherPercent = 0;
52
  const lines = languages.reduce((prev: any[], cur: any) => {
53
    const {name, percent, total_seconds} = cur;
54
    const line = formatLine(name, total_seconds, percent);
55
56
    if (name == 'Other' || prev.length >= MAX_RESULT - 1) {
57
      otherTotalSeconds += total_seconds;
58
      otherPercent += percent;
59
      return prev;
60
    }
61
62
    return [...prev, line];
63
  }, []);
64
65
  lines.push(formatLine('Other lang', otherTotalSeconds, otherPercent));
66
  if (lines.length === 0) return core.notice('No statistics for the last time period. Gist not updated');
67
68
  /**
69
   * Get gist filename
70
   */
71
  const octokit = new Octokit({auth: `token ${GH_TOKEN}`});
72
  const gist = await octokit.gists.get({gist_id: GIST_ID})
73
    .catch(error => core.setFailed('Action failed with error: Gist ' + error.message));
74
  if (!gist) return;
75
76
  const filename = Object.keys(gist.data.files || {})[0];
77
78
  /**
79
   * Update gist
80
   */
81
  await octokit.gists.update({
82
    gist_id: GIST_ID,
83
    files: {
84
      [filename]: {
85
        filename: title,
86
        content: lines.join('\n'),
87
      },
88
    },
89
  }).catch(error => core.setFailed('Action failed with error: Gist ' + error.message));
90
91
  summaryTable.push(['Gist updated', '✔']);
92
93
  /**
94
   * Print summary
95
   */
96
  const summary = core.summary
97
    .addHeading('Results')
98
    .addTable(summaryTable)
99
    .addBreak()
100
    .addLink('wakatime-gist', ACTION_URL);
101
102
  if (PRINT_SUMMARY) {
103
    await summary.write();
104
  } else {
105
    console.log(summary.stringify());
106
  }
107
})();